#pragma once
#include "task.hpp"
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>

// 先描述
class Channel
{
public:
    Channel(int fd, pid_t id) : _wfd(fd), _subid(id)
    {
        _name = "Channel-" + std::to_string(_wfd) + " " + std::to_string(_subid);
    }
    void Send(int code)
    {
        int n = write(_wfd, &code, sizeof(code));
        (void)n;
    }
    void Close()
    {
        close(_wfd);
    }
    void Wait()
    {
        pid_t rid = waitpid(_subid, nullptr, 0);
        (void)rid;
    }
    int Fd() { return _wfd; }
    pid_t SubId() { return _subid; }
    std::string Name() { return _name; }
    ~Channel()
    {}


private:
    int _wfd;
    pid_t _subid;
    std::string _name;
};

// 再组织
class channelManager
{
public:
    channelManager() : _next(0)
    {}
    void Insert(int wfd, pid_t subid)
    {
        _channels.emplace_back(wfd, subid);
    }
    Channel& Select()
    {
        auto& c = _channels[_next];
        _next++;
        _next %= _channels.size();
        return c;
    }
    void printChannel()
    {
        for (auto& channel : _channels)
            fmt::print("{}\n", channel.Name());
    }
    void stopSubProcess()
    {
        for (auto& channel : _channels)
        {
            channel.Close();
            fmt::print("关闭: {}\n", channel.Name());
        }
    }
    void waitSubProcess()
    {
        for (auto& channel : _channels)
        {
            channel.Wait();
            fmt::print("回收: {}\n", channel.Name());
        }
    }
    ~channelManager()
    {}
private:
    std::vector<Channel> _channels;
    int _next;
};

const int gdefaultnum = 5;

class processPool
{
public:
    processPool(int num) : _process_num(num)
    {
        _tm.Register(printLog);
        _tm.Register(Download);
        _tm.Register(Upload);
    }
    void Work(int rfd)
    {
        while (true)
        {
            int code = 0;
            ssize_t n = read(rfd, &code, sizeof(code));
            if (n > 0)
            {
                if (n != sizeof(code))
                    continue;
                fmt::print("子进程[{}]收到一个任务码: {}\n", getpid(), code);
                _tm.Execute(code);
            }
            else if (n == 0)
            {
                fmt::print("子进程退出\n");
                break;
            }
            else
            {
                fmt::print("读取错误\n");
                break;
            }
        }
    }
    bool Start()
    {
        for (int i = 0; i < _process_num; i++)
        {
            // 1. 创建管道
            int pipefd[2] = {0};
            int n = pipe(pipefd);
            if (n < 0)
                return false;

            // 2. 创建子进程
            pid_t subid = fork();
            if (subid < 0)
                return false;
            else if (subid == 0)
            {
                // 子进程
                // 3. 关闭不需要的文件描述符
                close(pipefd[1]);
                Work(pipefd[0]);
                close(pipefd[0]);
                _exit(3);
            }
            else
            {
                // 父进程
                // 3. 关闭不需要的文件描述符
                close(pipefd[0]);
                _cm.Insert(pipefd[1], subid);
            }
        }
        return true;
    }
    void Debug()
    {
        _cm.printChannel();
    }
    void Run()
    {
        // 1. 选择一个任务
        int taskcode = _tm.Code();

        // 2. 选择一个信道[子进程], 负载均衡的选择一个子进程, 完成任务
        auto& c = _cm.Select();
    }
    void Stop()
    {
        // 关闭父进程所有的wfd即可
        _cm.stopSubProcess();
        // 回收所有子进程
        _cm.waitSubProcess();
    }
    ~processPool()
    {}
private:
    channelManager _cm;
    int _process_num;
    taskManager _tm;
};
